package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.preloan.dto.insurance.*;
import cn.fl.preloan.enums.InsuranceEnum;
import cn.fl.commons.result.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.condition.InsCompInfoQueryCondition;
import cn.fl.insurance.condition.InsPlcBscInfoQueryCondition;
import cn.fl.insurance.condition.InsPlcStlQueryCondition;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.insurance.dto.InsCompInfoDTO;
import cn.fl.insurance.service.IInsCompInfoService;
import cn.fl.insurance.service.IInsPlcBscInfoService;
import cn.fl.insurance.service.IInsPlcStlDtlService;
import cn.fl.insurance.service.IInsPlcStlService;
import cn.fl.insurance.service.IInsTypInfoService;
import cn.fl.insurance.transform.InsCompInfoVOTransform;
import cn.fl.insurance.utils.ImportInsuranceList;
import cn.fl.insurance.vo.InsPlcBscInfoVO;
import cn.fl.insurance.vo.InsPlcStlDtlVO;
import cn.fl.insurance.vo.InsPlcStlVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 保单结算表 控制层
 */
@Controller
@RequestMapping("/insurance/insPlcStl")
public class InsPlcStlController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsPlcStlController.class);

	/**
	 * InsPlcStl 服务层BEAN
	 */
	@Autowired
	private IInsPlcStlService insPlcStlService;

	/**
	 * 数据字典 服务层BEAN
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * InsPlcBscInfo 服务层BEAN
	 */
	@Autowired
	private IInsPlcBscInfoService insPlcBscInfoService;
	/**
	 * InsCompInfo 服务层BEAN
	 */
	@Autowired
	private IInsCompInfoService insCompInfoService;
	@Autowired
	private ISysOrgApiService sysOrgApiService;
	@Autowired
	private IInsTypInfoService insTypInfoService;
	@Autowired
	private IInsPlcStlDtlService insPlcStlDtlService;
	/**
	 * 贷前服务
	 */
	@Autowired
	private cn.fl.preloan.IInsPlcBscInfoService iInsPlcBscInfoService;
	@Autowired
	private cn.fl.preloan.IInsPlcStlService iInsPlcStlService;

	/**
	 * 到保险结算列表页面
	 */
	@RequestMapping(value = "/toStlListPage.do", method = { RequestMethod.GET })
	public ModelAndView toStlListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toStlListPage", "加载保险结算toStlListPage列表页面.",
				CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insPlcStl/insPlcStlList");

		// 保险公司
		InsCompInfoQueryCondition qc = new InsCompInfoQueryCondition();
		qc.setCompLvl(1);
		List<InsCompInfoDTO> insCompList = this.insCompInfoService.searchList(qc);
		if (CollectionUtils.isNotEmpty(insCompList)) {
			mav.addObject("insCompList", JSON.toJSONString(InsCompInfoVOTransform.toVOList(insCompList)));
		}
		// 购买方式
		List<KeyValueVO> buyWayCdList = this.sysDictionaryApiService.getKvList(InsuranceConstant.CODE_INS_BUY_WAY_CD,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		if (CollectionUtils.isNotEmpty(buyWayCdList)) {
			mav.addObject("buyWayCdList", JSON.toJSONString(buyWayCdList));// 购买方式
		}
		// 结算状态，排除10、未开始结算状态
		List<KeyValueVO> stlStsCdList = this.sysDictionaryApiService.getKvList(
				InsuranceConstant.CODE_INS_PLC_STL_STS_CD, CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		if (CollectionUtils.isNotEmpty(stlStsCdList)) {
			for (KeyValueVO kv : stlStsCdList) {
				if (InsuranceConstant.CODE_INS_PLC_STL_STS_CD_10.equals(kv.getKey())) {
					stlStsCdList.remove(kv);
					break;
				}
			}
			mav.addObject("stlStsCdList", JSON.toJSONString(stlStsCdList));// 结算状态
		}
		mav.addObject("stlStsCd", InsuranceConstant.CODE_INS_PLC_STL_STS_CD_20);// 默认查询未结算数据
		// 事业部组织架构
		List<SysOrgDTO> buOrgCdList = this.sysOrgApiService
				.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
		mav.addObject("buOrgCdList", JSON.toJSONString(buOrgCdList));// 事业部
		// 险种
		/*InsTypInfoQueryCondition condition = new InsTypInfoQueryCondition();
		condition.setTypLvl(InsuranceConstant.CODE_INS_TYP_LVL_CD);// 保险父类
		List<KeyValueVO> insTypCdList = this.insTypInfoService.searchInsTypCdList(condition);// 保险种类
		*/

		List<KeyValueVO> insTypCdList = this.sysDictionaryApiService.getKvList(InsuranceConstant.CODE_INS_TYP_CD,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		mav.addObject("insTypCdList", JSON.toJSONString(insTypCdList));// 保险种类

		return mav;
	}

	/**
	 * 到结算记录列表页面
	 */
	@RequestMapping(value = "/toStlRecListPage.do", method = { RequestMethod.GET })
	public ModelAndView toStlRecListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toStlRecListPage", "加载结算记录toStlRecListPage列表页面.",
				CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insPlcStl/insPlcStlRecList");

		// 结算状态，排除10、未开始结算状态
		List<KeyValueVO> stlStsCdList = this.sysDictionaryApiService.getKvList(
				InsuranceConstant.CODE_INS_PLC_STL_STS_CD, CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		if (CollectionUtils.isNotEmpty(stlStsCdList)) {
			for (KeyValueVO kv : stlStsCdList) {
				if (InsuranceConstant.CODE_INS_PLC_STL_STS_CD_10.equals(kv.getKey())
						|| InsuranceConstant.CODE_INS_PLC_STL_STS_CD_20.equals(kv.getKey())) {
					stlStsCdList.remove(kv);
					break;
				}
			}
			mav.addObject("stlStsCdList", JSON.toJSONString(stlStsCdList));// 结算状态
		}
		// 事业部组织架构
		List<SysOrgDTO> buOrgCdList = this.sysOrgApiService
				.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
		mav.addObject("buOrgCdList", JSON.toJSONString(buOrgCdList));// 事业部
		return mav;
	}

	/**
	 * 初始化保险结算列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initStlList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initPlcStlList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		//InsPlcBscInfoQueryCondition qc = new InsPlcBscInfoQueryCondition();
		cn.fl.preloan.condition.InsPlcBscInfoQueryCondition qc = new cn.fl.preloan.condition.InsPlcBscInfoQueryCondition();
		// 设置查询条件？
		String plcNo = request.getParameter("plcNo");
		if (StringUtils.isNotEmpty(plcNo)) {
			qc.setPlcNo(plcNo);
		}
		String buyWayCd = request.getParameter("buyWayCd");
		if (StringUtils.isNotBlank(buyWayCd)) {
			qc.setBuyWayCd(buyWayCd);
		}
		String stlStsCd = request.getParameter("stlStsCd");
		if (StringUtils.isNotBlank(stlStsCd)) {
			qc.setStlStsCd(stlStsCd);
		}
		String buOrgCd = request.getParameter("buOrgCd");
		if (StringUtils.isNotBlank(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		String cstMgrNm = request.getParameter("cstMgrNm");
		if (StringUtils.isNotBlank(cstMgrNm)) {
			qc.setCstMgrNm(cstMgrNm);
		}
		String insCompId = request.getParameter("insCompId");
		if (StringUtils.isNotEmpty(insCompId)) {
			qc.setInsCompId(Long.valueOf(insCompId));
		}
		String insCompSubId = request.getParameter("insCompSubId");
		if (StringUtils.isNotEmpty(insCompSubId)) {
			qc.setInsCompId(Long.valueOf(insCompSubId));
		}
		String insCompSubNm = request.getParameter("insCompSubNm");
		if (StringUtils.isNotBlank(insCompSubNm)) {
			qc.setInsCompSubNm(insCompSubNm);
		}
		String plcBgTmStart = request.getParameter("plcBgTmStart");
		if (StringUtils.isNotBlank(plcBgTmStart)) {
			qc.setPlcBgTmStart(plcBgTmStart);
		}
		String plcBgTmEnd = request.getParameter("plcBgTmEnd");
		if (StringUtils.isNotBlank(plcBgTmEnd)) {
			qc.setPlcBgTmEnd(plcBgTmEnd);
		}
		String paySchNo = request.getParameter("paySchNo");
		if (StringUtils.isNotBlank(paySchNo)) {
			qc.setPaySchNo(paySchNo.trim());
		}
		String cstNm = request.getParameter("cstNm");
		if (StringUtils.isNotBlank(cstNm)) {
			qc.setCstNm(cstNm.trim());
		}
		String insTypCd = request.getParameter("insTypCd");
		if (StringUtils.isNotBlank(insTypCd)) {
			qc.setInsTypCd(insTypCd);
		}
		qc.setStlStsCdFlag("1");// 过滤未开始结算的保单

		//page.setCondition(qc);

		ResponseData responseData = iInsPlcBscInfoService.searchInsPlcStlListPageByCondition(page.getEveryPage(), page.getCurrentPage(), qc,
				InsuranceEnum.CODE_INS_SYS_CD.getCode(), InsuranceEnum.CODE_INS_ORG_CD.getCode());
		BaseLogUtils.info(logger, "initInsPlcBscInfoList",
				"贷前--初始化保单结算列表页面数据.request:" + JSONObject.toJSONString(qc) + ",response:" + JSONObject.toJSONString(responseData),
				CurrentThreadContext.getCurrentUserName());
		PageResponse<InsPlcBscInfoDTO> pageResponse = null;
		List<InsPlcBscInfoVO> voList = new ArrayList<>();
		InsPlcBscInfoVO insPlcBscInfoVO = null;
		if (responseData != null && responseData.getData() != null) {
			pageResponse = (PageResponse<InsPlcBscInfoDTO>) responseData.getData();
			List<InsPlcBscInfoDTO> list = pageResponse.getList();
			for (InsPlcBscInfoDTO insPlcBscInfoDTO : list) {
				insPlcBscInfoVO = new InsPlcBscInfoVO();
				BeanUtils.copyProperties(insPlcBscInfoDTO,insPlcBscInfoVO);
				voList.add(insPlcBscInfoVO);
			}
		}
		/*Pager pager = this.insPlcStlService.searchStlListPage(page);
		List<InsPlcBscInfoVO> list = (List<InsPlcBscInfoVO>) pager.getResultList();*/
		ListPageVO<InsPlcBscInfoVO> listPage = new ListPageVO<InsPlcBscInfoVO>(voList, pageResponse.getTotalCount());		return listPage;
	}

	/**
	 * 初始化结算记录列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initStlRecList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initPlcStlRecList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		cn.fl.preloan.condition.InsPlcStlQueryCondition qc = new cn.fl.preloan.condition.InsPlcStlQueryCondition();
		// 设置查询条件？
		String stlNo = request.getParameter("stlNo");
		if (StringUtils.isNotEmpty(stlNo)) {
			qc.setStlNo(stlNo.trim());
		}

		String insCompNm = request.getParameter("insCompNm");
		if (StringUtils.isNotEmpty(insCompNm)) {
			qc.setInsCompNm(insCompNm.trim());
		}
		String stlBgTm = request.getParameter("stlBgTm");
		if (StringUtils.isNotEmpty(stlBgTm)) {
			qc.setStlCompBgTm(stlBgTm);
		}
		String stlEndTm = request.getParameter("stlEndTm");
		if (StringUtils.isNotEmpty(stlEndTm)) {
			qc.setStlCompEndTm(stlEndTm);
		}
		String stlStsCd = request.getParameter("stlStsCd");
		if (StringUtils.isNotBlank(stlStsCd)) {
			qc.setStlStsCd(stlStsCd);
		}
		/*page.setCondition(qc);

		BaseLogUtils.info(logger, "initInsPlcStlList", "初始化InsPlcStl列表页面数据.DATA:" + JSONObject.toJSONString(page),
				CurrentThreadContext.getCurrentUserName());
		Pager pager = this.insPlcStlService.searchListPage(page);
		List<InsPlcStlVO> list = (List<InsPlcStlVO>) pager.getResultList();
		ListPageVO<InsPlcStlVO> listPage = new ListPageVO<InsPlcStlVO>(list, pager.getTotalCount());*/
		GetInsPlcStlPageRequest getRequest = new GetInsPlcStlPageRequest();
		getRequest.setPageNo(page.getCurrentPage());
		getRequest.setPageSize(page.getEveryPage());
		getRequest.setCondition(qc);
		ResponseData responseData = iInsPlcStlService.searchListPage(getRequest);
		BaseLogUtils.info(logger, "initInsPlcStlList", "贷前--初始化结算记录列表页面.request:" + JSONObject.toJSONString(getRequest)
				+ ",response:" + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
		PageResponse<InsPlcStlDTO> pageResponse = null;
		List<InsPlcStlVO> list = new ArrayList<>();
		InsPlcStlVO insPlcStlVO = null;
		ListPageVO<InsPlcStlVO> listPage = new ListPageVO<>();
		if (responseData != null && responseData.getData() != null) {
			pageResponse = (PageResponse<InsPlcStlDTO>) responseData.getData();
			List<InsPlcStlDTO> insPlcStlDTOS = pageResponse.getList();
			for (InsPlcStlDTO insPlcStlDTO : insPlcStlDTOS) {
				insPlcStlVO = new InsPlcStlVO();
				BeanUtils.copyProperties(insPlcStlDTO,insPlcStlVO);
				list.add(insPlcStlVO);
			}
			listPage = new ListPageVO<InsPlcStlVO>(list, pageResponse.getTotalCount());
		}
		BaseLogUtils.info(logger, "initInsPlcStlList", "贷前--初始化结算记录列表页面.pageResponse:" + JSONObject.toJSONString(pageResponse)
				+ ",list:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载InsPlcStl Add页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insPlcStl/insPlcStlModify");
		// 加载数据字典数据、传值等 ？

		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载InsPlcStl Modify页面.", CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insPlcStl/insPlcStlModify");
		// 加载数据字典数据、传值等 ？
		String id = request.getParameter("id");
		String stlAmt = request.getParameter("stlAmt");
		String stlNo = request.getParameter("stlNo");
		String actStlAmt = request.getParameter("actStlAmt");
		mav.addObject("id", id);
		mav.addObject("stlAmt", stlAmt);
		mav.addObject("stlNo", stlNo);
		mav.addObject("actStlAmt", actStlAmt);
		return mav;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = { RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeInsPlcStlByIds(HttpServletRequest request, HttpServletResponse response)
			throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeInsPlcStlByIds", "删除InsPlcStl数据,主键参数为空!",
					CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			BaseLogUtils.info(logger, "removeInsPlcStlByIds", "删除InsPlcStl数据,request:" + JSONObject.toJSONString(idsList), CurrentThreadContext.getCurrentUserName());
			for (Long id : idsList) {
				DeleteInsPlcStlByIdRequest deleteRequest = new DeleteInsPlcStlByIdRequest();
				deleteRequest.setId(id);
				deleteRequest.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				ResponseData responseData = iInsPlcStlService.deleteInsPlcStl(deleteRequest);
				BaseLogUtils.info(logger, "removeInsPlcStlByIds", "删除InsPlcStl数据,request:" + JSONObject.toJSONString(deleteRequest)
						+ ",response:" + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
				/*boolean success = this.insPlcStlService.removeByIds(idsList);*/
				if (responseData.getCode().equals(ResponseData.FAIL_CODE)) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
					BaseLogUtils.info(logger, "removeInsPlcStlByIds", "删除InsPlcStl数据失败,ID:" + id.toString(),
							CurrentThreadContext.getCurrentUserName());
				}
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeInsPlcStlByIds",
					"删除InsPlcStl数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeInsPlcStlByIds",
					"删除InsPlcStl数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 保单结算
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/stlByIds.do", method = { RequestMethod.POST })
	@ResponseBody
	public DataResultVO stlByInsPlcIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "stlByInsPlcIds", "保单结算,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}

		try {
			// boolean success = this.insPlcStlService.removeByIds(idsList);
			boolean success = false;
			if (!success) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "stlByInsPlcIds", "保单结算失败,ID:" + idsList.toString(),
						CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "stlByInsPlcIds", "保单结算成功,ID:" + idsList.toString(),
					CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "stlByInsPlcIds", "保单结算失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "stlByInsPlcIds",
					"保单结算失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object getInsPlcStlById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if (StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getInsPlcStlById", "获取InsPlcStl数据,主键参数为空.",
					CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			InsPlcStlVO vo = this.insPlcStlService.selectById(Long.valueOf(id));
			if (null == vo) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getInsPlcStlById", "获取InsPlcStl数据不存在,ID:" + id,
						CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getInsPlcStlById", "获取InsPlcStl数据成功,ID:" + id,
					CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getInsPlcStlById", "获取InsPlcStl数据失败,ID:" + id + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getInsPlcStlById",
					"获取InsPlcStl数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增保单结算记录
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addInsPlcStl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		String ids = request.getParameter("ids");
		if (StringUtils.isEmpty(ids)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("未找到保单信息");
			BaseLogUtils.info(logger, "addInsPlcStl", "结算保单数据,保单IDS参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		try {
			AddInsPlcStlRequest addRequest = new AddInsPlcStlRequest();
			addRequest.setIds(idsList);
			addRequest.setCrtUserId(CurrentThreadContext.getCurrentUserId());
			addRequest.setCrtTm(new Date());
			ResponseData responseData = iInsPlcStlService.addPlcStl(addRequest);
			BaseLogUtils.info(logger, "addInsPlcStl", "贷前--新增InsPlcStl数据，request:" + JSONObject.toJSONString(addRequest)
					+ ",response: " + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
			//boolean flag = this.insPlcStlService.addPlcStl(idsList);
			if (responseData.getCode().equals(ResponseData.FAIL_CODE)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + "结算汇总数据失败");
				BaseLogUtils.info(logger, "addInsPlcStl",
						"新增InsPlcStl结算汇总数据失败,IDS.DATA:" + JSONObject.toJSONString(idsList),
						CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.info(logger, "addInsPlcStl",
					"新增InsPlcStl数据失败.DATA:" + JSONObject.toJSONString(idsList) + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.error(logger, "addInsPlcStl",
					"新增InsPlcStl数据失败,系统错误.DATA:" + JSONObject.toJSONString(idsList) + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyInsPlcStl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		InsPlcStlVO entity = null;
		try {
			entity = this.getRequestParamForInsPlcStl(request);
			if (entity.getId() == null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyInsPlcStl", "修改InsPlcStl信息,主键参数为空！.ID:" + entity.getId(),
						CurrentThreadContext.getCurrentUserName());
				return result;
			}

			ModifyInsPlcStlRequest modifyRequest = new ModifyInsPlcStlRequest();
			InsPlcStlDTO insPlcStlDTO = new InsPlcStlDTO();
			//ACT_STL_AMT=?, STL_STS_CD=?, STL_NO=?, STL_AMT=?, STL_REM=? WHERE ID=?
			insPlcStlDTO.setId(entity.getId());
			insPlcStlDTO.setStlAmt(entity.getStlAmt());
			insPlcStlDTO.setStlNo(entity.getStlNo());
			insPlcStlDTO.setActStlAmt(entity.getActStlAmt());
			insPlcStlDTO.setStlRem(entity.getStlRem());
			insPlcStlDTO.setStlStsCd(entity.getStlStsCd());
			insPlcStlDTO.setStlCompTm(entity.getStlCompTm());
			modifyRequest.setInsPlcStlDTO(insPlcStlDTO);
			InsPlcBscInfoDTO insPlcBscInfoDTO = new InsPlcBscInfoDTO();
			insPlcBscInfoDTO.setStlTm(entity.getStlCompTm());
			insPlcBscInfoDTO.setId(entity.getId());
			insPlcBscInfoDTO.setStlStsCd(entity.getStlStsCd());
			modifyRequest.setInsPlcBscInfoDTO(insPlcBscInfoDTO);
			BaseLogUtils.info(logger, "modifyInsPlcStl", "贷前--修改InsPlcStl数据request:" + JSONObject.toJSONString(modifyRequest)
					, CurrentThreadContext.getCurrentUserName());
			ResponseData responseData = iInsPlcStlService.modifyInsPlcStl(modifyRequest);
			BaseLogUtils.info(logger, "modifyInsPlcStl", "贷前--修改InsPlcStl数据response: " + JSONObject.toJSONString(responseData), CurrentThreadContext.getCurrentUserName());
			//boolean success = this.insPlcStlService.modify(entity);
			if (responseData.getCode().equals(ResponseData.FAIL_CODE)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyInsPlcStl", "修改InsPlcStl数据.DATA:" + JSONObject.toJSONString(entity),
						CurrentThreadContext.getCurrentUserName());
				return result;
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.info(logger, "modifyInsPlcStl",
					"修改InsPlcStl数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.error(logger, "modifyInsPlcStl",
					"修改InsPlcStl数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 导出结算列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportStlList.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO exportStlList(HttpServletRequest request, HttpServletResponse response) {
		InsPlcBscInfoQueryCondition qc = new InsPlcBscInfoQueryCondition();
		// 设置查询条件？
		String plcNo = request.getParameter("plcNo");
		if (StringUtils.isNotEmpty(plcNo)) {
			qc.setPlcNo(plcNo);
		}
		String buyWayCd = request.getParameter("buyWayCd");
		if (StringUtils.isNotBlank(buyWayCd)) {
			qc.setBuyWayCd(buyWayCd);
		}
		String stlStsCd = request.getParameter("stlStsCd");
		if (StringUtils.isNotBlank(stlStsCd)) {
			qc.setStlStsCd(stlStsCd);
		}
		String buOrgCd = request.getParameter("buOrgCd");
		if (StringUtils.isNotBlank(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		String cstMgrNm = request.getParameter("cstMgrNm");
		if (StringUtils.isNotBlank(cstMgrNm)) {
			qc.setCstMgrNm(cstMgrNm);
		}
		String insCompId = request.getParameter("insCompId");
		if (StringUtils.isNotEmpty(insCompId)) {
			qc.setInsCompId(Long.valueOf(insCompId));
		}
		String insCompSubId = request.getParameter("insCompSubId");
		if (StringUtils.isNotEmpty(insCompSubId)) {
			qc.setInsCompId(Long.valueOf(insCompSubId));
		}
		String insCompSubNm = request.getParameter("insCompSubNm");
		if (StringUtils.isNotBlank(insCompSubNm)) {
			qc.setInsCompSubNm(insCompSubNm);
		}
		String plcBgTmStart = request.getParameter("plcBgTmStart");
		if (StringUtils.isNotBlank(plcBgTmStart)) {
			qc.setPlcBgTmStart(plcBgTmStart);
		}
		String plcBgTmEnd = request.getParameter("plcBgTmEnd");
		if (StringUtils.isNotBlank(plcBgTmEnd)) {
			qc.setPlcBgTmEnd(plcBgTmEnd);
		}
		String paySchNo = request.getParameter("paySchNo");
		if (StringUtils.isNotBlank(paySchNo)) {
			qc.setPaySchNo(paySchNo.trim());
		}
		String cstNm = request.getParameter("cstNm");
		if (StringUtils.isNotBlank(cstNm)) {
			qc.setCstNm(cstNm.trim());
		}
		qc.setStlStsCdFlag("1");// 过滤未开始结算的保单

		BaseLogUtils.info(logger, "exportStlRecList", "导出保单结算清单列表==");
		return this.insPlcStlService.exportPlcStlList(qc);
	}

	/**
	 * 导出结算记录列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/exportStlRecList.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO exportStlRecList(HttpServletRequest request, HttpServletResponse response) {
		InsPlcBscInfoQueryCondition qc = new InsPlcBscInfoQueryCondition();
		// 设置查询条件？
		String stlStsCd = request.getParameter("stlStsCd");
		if (StringUtils.isNotBlank(stlStsCd)) {
			qc.setStlStsCd(stlStsCd);
		}
		String insCompSubNm = request.getParameter("insCompNm");
		if (StringUtils.isNotBlank(insCompSubNm)) {
			qc.setInsCompSubNm(insCompSubNm);
		}
		String plcBgTmStart = request.getParameter("plcBgTmStart");
		if (StringUtils.isNotBlank(plcBgTmStart)) {
			qc.setPlcBgTmStart(plcBgTmStart);
		}
		String plcBgTmEnd = request.getParameter("plcBgTmEnd");
		if (StringUtils.isNotBlank(plcBgTmEnd)) {
			qc.setPlcBgTmEnd(plcBgTmEnd);
		}
		String stlNo = request.getParameter("stlNo");
		if (StringUtils.isNotBlank(stlNo)) {
			qc.setStlNo(stlNo.trim());
		}
		BaseLogUtils.info(logger, "exportStlRecList", "导出保单结算记录列表==");
		return this.insPlcStlService.exportPlcStlRecList(qc);
	}

	/**
	 * 查询保单总保费金额、结算总金额
	 */
	@RequestMapping(value = "/getTtlStlAmt.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object getTtlStlAmt(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES);
		//InsPlcBscInfoQueryCondition qc = new InsPlcBscInfoQueryCondition();
		cn.fl.preloan.condition.InsPlcBscInfoQueryCondition qc = new cn.fl.preloan.condition.InsPlcBscInfoQueryCondition();
		// 设置查询条件？
		String plcNo = request.getParameter("plcNo");
		if (StringUtils.isNotEmpty(plcNo)) {
			qc.setPlcNo(plcNo);
		}
		String buyWayCd = request.getParameter("buyWayCd");
		if (StringUtils.isNotBlank(buyWayCd)) {
			qc.setBuyWayCd(buyWayCd);
		}
		String stlStsCd = request.getParameter("stlStsCd");
		if (StringUtils.isNotBlank(stlStsCd)) {
			qc.setStlStsCd(stlStsCd);
		}
		String buOrgCd = request.getParameter("buOrgCd");
		if (StringUtils.isNotBlank(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		String cstMgrNm = request.getParameter("cstMgrNm");
		if (StringUtils.isNotBlank(cstMgrNm)) {
			qc.setCstMgrNm(cstMgrNm);
		}
		String insCompId = request.getParameter("insCompId");
		if (StringUtils.isNotEmpty(insCompId)) {
			qc.setInsCompId(Long.valueOf(insCompId));
		}
		String insCompSubId = request.getParameter("insCompSubId");
		if (StringUtils.isNotEmpty(insCompSubId)) {
			qc.setInsCompId(Long.valueOf(insCompSubId));
		}
		String insCompSubNm = request.getParameter("insCompSubNm");
		if (StringUtils.isNotBlank(insCompSubNm)) {
			qc.setInsCompSubNm(insCompSubNm);
		}
		String plcBgTmStart = request.getParameter("plcBgTmStart");
		if (StringUtils.isNotBlank(plcBgTmStart)) {
			qc.setPlcBgTmStart(plcBgTmStart);
		}
		String plcBgTmEnd = request.getParameter("plcBgTmEnd");
		if (StringUtils.isNotBlank(plcBgTmEnd)) {
			qc.setPlcBgTmEnd(plcBgTmEnd);
		}
		String paySchNo = request.getParameter("paySchNo");
		if (StringUtils.isNotBlank(paySchNo)) {
			qc.setPaySchNo(paySchNo.trim());
		}
		String cstNm = request.getParameter("cstNm");
		if (StringUtils.isNotBlank(cstNm)) {
			qc.setCstNm(cstNm.trim());
		}
		qc.setStlStsCdFlag("1");// 过滤未开始结算的保单
		//BaseLogUtils.info(logger, "getTtlStlAmt", "查询保单总保费金额、结算总金额==");
		GetTtlStlAmtRequest getRequest = new GetTtlStlAmtRequest();
		getRequest.setCondition(qc);
		ResponseData responseData = iInsPlcBscInfoService.getTtlStlAmt(getRequest);
		BaseLogUtils.info(logger, "getTtlStlAmt", "贷前--查询保单总保费金额、结算总金额,request：" + JSONObject.toJSONString(qc)
				+ ",response:" + JSONObject.toJSONString(responseData));
		Map<String, Long> map = null;
		if (responseData != null && responseData.getData() !=null) {
			map = (Map<String, Long>) responseData.getData();
			result.setData(map);
		}
		//return this.insPlcStlService.getTtlStlAmt(qc);
		return result;
	}

	/**
	 * 获取请求参数
	 *
	 * @param request
	 *            请求
	 * @return
	 */
	private InsPlcStlVO getRequestParamForInsPlcStl(HttpServletRequest request) throws BaseException {
		// 获取参数
		String id = request.getParameter("id");// 主键
		String actStlAmt = request.getParameter("actStlAmt");
		String stlStsCd = request.getParameter("stlStsCd");
		String stlTm = request.getParameter("stlTm");
		String stlRem = request.getParameter("stlRem");

		// 验证参数并赋值
		InsPlcStlVO entity = new InsPlcStlVO();
		if (StringUtils.isBlank(actStlAmt)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "实际结算金额不能为空.");
		}
		entity.setActStlAmt(DecimalUtils.convertYuanToFen(Double.valueOf(actStlAmt)));
		if (StringUtils.isBlank(stlTm)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "结算时间不能为空.");
		}
		entity.setStlCompTm(DateUtils.formatStringToDate(stlTm, DateUtils.YYYY_MM_DD));
		entity.setStlRem(stlRem);
		entity.setStlStsCd(stlStsCd);
		Date tm = new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		} else {
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		}
		return entity;
	}

	/*********************
	 * 到保单结算记录导入列表面
	 *********************/
	@RequestMapping(value = "/toInsPlcStlRecImportPage.do", method = { RequestMethod.GET })
	public ModelAndView toInsPlcStlRecImportPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toInsPlcStlRecImportPage", "加载toInsPlcStlRecImportPage保单结算记录导入列表面.",
				CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insPlcStl/insPlcStlRecImportList");
		String filePath = request.getParameter("filePath");// 文件路径
		mav.addObject("filePath", filePath);
		List<InsPlcStlDtlVO> list = ImportInsuranceList.importInsPlcStlDtlXlsx(filePath);
		if (CollectionUtils.isNotEmpty(list)) {
			mav.addObject("insPlcStlRecList", JSON.toJSONString(list));
			System.out.println(JSON.toJSONString(list));
			mav.addObject("success", "true");// 导入保单结算记录数据验证通过
		} else {
			mav.addObject("success", "false");// 无保单结算记录数据
		}
		return mav;
	}

	/***********************
	 * 保单结算记录批量导入
	 ***********************/
	@RequestMapping(value = "/importInsPlcStlRec.do", method = { RequestMethod.POST })
	@ResponseBody
	public DataResultVO importInsPlcStlRec(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "保单结算记录导入成功");
		String filePath = request.getParameter("filePath");// 文件路径
		List<InsPlcStlDtlVO> list = ImportInsuranceList.importInsPlcStlDtlXlsx(filePath);
		if (CollectionUtils.isNotEmpty(list)) {
			Date mdfTm = new Date();
			for (InsPlcStlDtlVO vo : list) {
				vo.setId(vo.getStlDtlId());// 结算明细编号
				vo.setStlId(vo.getStlId());// 结算编号
				vo.setPlcNo(vo.getPlcNo());// 保单号
				vo.setMdfTm(mdfTm);// 修改时间
				vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());// 修改人
				if (vo.getActStlAmts() != null && !vo.getActStlAmts().equals("")) {
					Long actStlAmt = DecimalUtils
							.convertYuanToFen(Double.valueOf(vo.getActStlAmts().trim().replaceAll("￥|\\,", "")));
					vo.setActStlAmt(actStlAmt);// 实际结算金额
				}
			}
			boolean flag = this.insPlcStlDtlService.modify(list);
			if (flag) {
				BaseLogUtils.info(logger, "importInsPlcStlRec", "保单结算金额记录导入成功.DATA:" + filePath,
						CurrentThreadContext.getCurrentUserName());
			} else {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "importInsPlcStlRec", "保单结算金额记录导入失败.导入数据为空",
						CurrentThreadContext.getCurrentUserName());
			}
		}
		return result;
	}
}
